
//////////////////////// INITIALIZING ///////////////
// All starting up
$(document).ready(function() {	
	$('#intro_sentence').show();		
	ajaxServiceFilter($('select#department'));
	
						
});

/////////////////////// SHOW / HIDE COMMON INFO ///////////////
// 
$(document).ready(function() {
	$('#show_hide_common_info').click(function() {
		if ($('#show_hide_common_info').attr('title') == "Ẩn") {
			$('#show_hide_common_info').attr('src', '../images/expand.png');
			$('#show_hide_common_info').attr('title', 'Hiện');
		} else {
			$('#show_hide_common_info').attr('src', '../images/collapse.png');
			$('#show_hide_common_info').attr('title', 'Ẩn');			
		}
		$('#common_info_frame').toggle();
	});
});

/////////////////////// UPDATE COMMON INFO CLICK EVENT ///////////////
// 

function updateSale() {	
	if ($('#sale_program :selected').val() != '') {
		$('#insurance').attr('checked', '');
	} 		
}

function updateInsurance() {
	if ($('#insurance').attr('checked') == true) {
		$('#sale_program :first-child').attr('selected', 'selected');
	}
}


function cancelUpdate() {
	$('#edit_common_info').hide();
	$('#view_common_info').show();	
}

function performEditCommonInfo() {	
	$('#view_common_info').hide();
	$('#edit_common_info').show();
	$('#ticket_note').val($('#ticket_note_view').text());
}

function udpateCommonInfo() {	
	$.ajax({
		type:		"POST",
		url:		"../Ticket/UpdateCommonInfoAjax?set_ajax_view",
		data:		"ticket_id=" + $('input#ticket_id').val() +					
					"&sale_program_store_id=" + $('#sale_program').val() +
					"&insurance=" + $('#insurance').attr('checked') + 					
					"&examination_type_id=" + $('#examination_type').val() +
					"&ticket_note=" + $('#ticket_note').val(),
		beforeSend:	function() {
			$('div#loading').show();
			$('#save_common_info_btn').attr('disabled', 'disabled');				
		},
		complete:	function() {								
			$('div#loading').hide();				
		}, 
		success:	function(data) {								
			$('#status_message span:first-child').text(_('Updating succeed'));
			$('#status_message').slideDown().slideUp(5000);		
			$('#common_info_frame').html(data);
			updatePrice($('select#service'));
			viewOpenTicket($('input#ticket_id').val());					
		}	
	});
}	

/////////////////////// START BUTTON ///////////////
// Start button
$(document).ready(function(){
 	$('#start').click(function() {
 		if($('#ticket_item').find('tr').length == 1) {
 			var message = _("Don't find any service");
 			//close 				
 			var buttons = {};
 			buttons[_('Close')] = function() {
 					$(this).dialog('close');		
 				};
 			generalDialog(null,null,message,null,{
 					autoOpen: true,			
 					bgiframe: true,
 					resizable: true,
 					modal: true,							
 					buttons: buttons
 				});
		} else {
			initializingTicket();					
		}
 	});
});

function initializingTicket() {
	
	$.ajax({
		type: 	    "GET",
		url:		"../Ticket/InitializingTicketAjax?set_ajax_view",
		data:		"ticket_id=" + $('input#ticket_id').val() +
					"&patient_id=" + $('input#patient_id').val(),		
		dataType: 	"json",
		beforeSend:	function() {
			$('div#loading').show('fast');				
		},
		complete:	function() {							
			$('div#loading').hide('fast');
		}, 
		success:	function(data) {
			if (data.status == 'closed') {				
				cannotDo(data.message);
				return;
			} else if (data.status == 'open') {
				var message = _('Next location: <span class="bigImpression">{0}</span>', data.message) ;
				//no button 
				generalDialog(null,null,message);
				window.location = data.redirectLink;				
				//setTimeout("redirect('../Queue/receptionistQueue')", 4000);
			}					
		}
	});
}

function redirect(url) {
	window.location=url;
}

function showTransferMessage(roomName) {
	var message = _('Next location: <span class="bigImpression">{0}</span>', roomName) ;	
	//no button
	generalDialog(null,null,message);
}


//////////////////////// DELETE TICKET ///////////////
// Cancel button - delete the ticket
// 
jQuery(document).ready(function() {
	$('#cancel').click(function() {	
		promptConfirm(_('Delete'),_('Are you sure to delete this ticket?') 
				+ '<p>' 
				+ _('<span class="impression">Notice:</span> Deleting will fully remove examination info (prescription, surgery...) of this encounter ticket.') 
				+ '</p>', 
				function() {					
					deleteTicketSubmit();
					return true;
				},'YesNo','warn',_('No'));								
	});
});

function deleteTicketSubmit() {
	var treeItem = '<option id="noTicket" value="0" selected="selected">' + _('Not yet') + '</option>';	
	$('#newTicket').remove();
	$('#newTicketGroup').html(treeItem);
	$.ajax({
		type:		"GET",
		url:		"../Ticket/DeleteAjax/?set_ajax_view",
		data:		"ticket_id=" + $('input#ticket_id').val(),
		beforeSend:	function() {
			$('div#loading').show();				
		},		
		complete:	function() {							
			$('div#loading').hide();
		}, 
		success:	function(result) {
			if (result == true) {
				$('#add_ticket').hide();				
				$('#add_ticket_button').show();
				$('#intro_sentence').show();
			} else {
				var message = _("Patient is examining"); 
				if (result == 'closed') {
					message = _("Ticket was closed");
				}
				message = _("{0} Can't delete the ticket", message);
				
				cannotDo(message);					
			}			
		}			
	});
}

function cannotDo(message) {
	//button close	
	var buttons = {};
	buttons[_('Close')] = function() {
			$(this).dialog('close');		
		};
	generalDialog(null,null,message,null,{
			autoOpen: true,			
			bgiframe: true,
			resizable: true,
			modal: true,							
			buttons: buttons
		},_('Close'));
	// reset the current_id to make loadPage able to run
	current_id = '';
	loadPage('pageContent', '../Ticket/DisplayAjax', $('input#patient_id').val());
}

//////////////////////// ADD NEW TICKET ///////////////
//
$(document).ready(function() {
	$('#add_ticket_button').click(function() {
			addTicket();	
	});
});

function addTicket() {
	$('#ticket_item').find('tr:first').siblings().remove();				
	$.ajax({
		type:		"GET",			
		url:		"../Ticket/AddAjax/?set_ajax_view",
		data:		"patient_id=" + $("input#patient_id").val(),
		dataType:	"json",
		beforeSend:	function() {
			$('div#loading').show('fast');
		},
		complete:	function() {
			$('div#intro_sentence').hide();			
			$('div#loading').hide('fast');
		}, 		
		success:	function(data) {										
			$('input#ticket_id').attr('value', data.ticket_id);
			$('span#open_ticket_name').text(data.ticket_name);				
			var treeItem = '<option id="newTicket" value="N' + data.ticket_id + '" selected="selected">' + data.ticket_name + '</option>';	
			$('#noTicket').remove();
			$('#newTicketGroup').html(treeItem);
			// ticket_item table			
			$('#ticket_item').hide().find('tbody tr').remove();																		
			$('#add_ticket').show();
			$('#add_ticket_button').hide();		
			$('#view_closed_ticket').hide();
			
			// ticket common info section
			$('#common_info_frame').html(data.ticket_common_info);			
			performEditCommonInfo();
		}
	});
}

//////////////////////// FILTER DEPARTMENT, SERVICE, ROOM ///////////////
// Department, Service, Room Filter ajax

jQuery(document).ready(function() {	
	$('select#department').change(function() {				
		ajaxServiceFilter($(this));		
	});
	
	$('select#service').change(function() {
		ajaxRoomFilter($(this));		
	});
});

// filter service by department
function ajaxServiceFilter(department) {
	$.ajax ({
		type:		"GET",
		url:		'../Department/FilterServiceAjax?set_ajax_view',
		data:		'department_id=' + department.val(),
		beforeSend:	function() {
			$('input#add_service').attr('disabled', 'disabled');
		},		
		success: function(data) {
			$('select#service').html(data);			
			ajaxRoomFilter($('select#service'));								
		}
	});	
}

function updatePrice(service) {
	if ($('#ticket_id').val() > 0) {
		$.ajax ({
			type:		"GET",
			url:		'../Service/getPatientPriceAjax?set_ajax_view',
			data:		'service_id=' + service.val() +
						'&ticket_id=' + $('#ticket_id').val(),							
			success: function(data) {
				$('#service_price').text(data);
			}
		});	
	}	
}

// filter room by service
function ajaxRoomFilter(service) {	
	updatePrice(service);
		
	$.ajax ({
		type:		"GET",
		url:		'../Service/FilterRoomAjax?set_ajax_view',
		data:		'service_id=' + service.val(),
		beforeSend:	function() {
			$('input#add_service').attr('disabled', 'disabled');
		},
		complete: function() {
				$('input#add_service').removeAttr('disabled');
		},
		success: function(data) {			
			$('select#service_room').html(data);							
		}
	});			
}



//////////////////////// ADD SERVICE ///////////////
// add Service ajax
			
jQuery(document).ready(function() {				
	$('input#add_service').click(function() {		
		addServiceAjax();
	});
});

function addServiceAjax() {
	
	$.ajax({
		url:		"../Ticket/CheckReadyToAddServiceAjax?set_ajax_view",
		data:		"ticket_id=" 		+ $('input#ticket_id').val() +
					"&service_room_id="	+ $('select#service_room').val(),
		dataType:	"json",							
		success:	function(result) {
			// ticket is closed
			if (result.status == 0) {
				cannotDo(result.body);
				return;
			}							
			
			// duplicated service
			if (result.status == 1) {
				promptConfirm('', result.body, function() {											
						addServiceSubmit();
						return true;
						},'NextCancel','',_('Cancel'));
			}
			
			// ready
			if (result.status == -1) {
				addServiceSubmit();
			}						
		}
	});
	
	
}

function addServiceSubmit() {
	
	$.ajax ({
		type: 		"GET",
		url:		"../Ticket/AddServiceAjax?set_ajax_view",
		data:		"ticket_id=" 		+ $('input#ticket_id').val() +
					"&service_room_id="	+ $('select#service_room').val(),					
		beforeSend:	function() {
			$('input#add_service').attr('disabled', 'disabled');			
			$('div#loading').show('fast');
		},
		complete:	function() {
			$('input#add_service').removeAttr('disabled');
			$('div#loading').hide('slow')
		},
		success:	function(result) {									
			viewOpenTicket($('#ticket_id').val());											
		}
	});
}

/////////////////////////////// TEST MANIPULATION ////////////////////

	//////////// REGISTER POPUP WINDOW AND CLOSE BUTTON //////////////
	//
	
	
	
	$(document).ready(function() {			
		$('#add_package').click(function() {	
			appendServicePackage($('#service_package').val());		
			//popupServicePackage($('#service_package').val());
		});
		// dont pop up the package
		/*
		$('#close_package').click(function() {
			$('div#package_detail_dialog').jqmHide();
		});
		
		$('#append_package').click(function() {
			appendServicePacakge($('#service_package').val());
		});
		*/
	});
	
	//////////////////////// SERVICE PACKAGE ///////////
	//
	function popupServicePackage(packageId) {		
		$.ajax({
			type:		"GET",
			url:		"../Package/PackageDetailAjax?set_ajax_view",
			data: 		"package_id=" + packageId,
			dataType: 	"json",
			beforeSend:	function() {
				$('#add_package').attr('disabled', 'disabled');
				$('div#loading').show('fast');
			},
			complete: function(){			
				$('#add_package').removeAttr('disabled');
				$('div#loading').hide('fast');
			},
			success:	function(data) {
				$('#package_name').text(data.name);
				$('#package_note').text(data.note);
			
				$('table#package_detail tbody').html(data.body);
				generalDialog('package_detail_dialog',null,null,null,{
					autoOpen: true,			
					bgiframe: true,
					resizable: true,		
					width: 700,
					height: 400,
					modal: true					
				});
			}			
		});
	}	
	
	function appendServicePacakge(packageId) {
		$.ajax({
			type:		"GET",
			url:		"../Ticket/AppendPackageAjax?set_ajax_view",
			data: 		"package_id=" + packageId +
						"&ticket_id=" + $('#ticket_id').val(),			
			beforeSend:	function() {
				$('#add_package').attr('disabled', 'disabled');
				$('div#loading').show('fast');
				//$('div#package_detail_dialog').jqmHide();
			},
			complete: function(){			
				$('#add_package').removeAttr('disabled');
				$('div#loading').hide('fast');
			},
			success:	function(data) {								
				if (data == 1) {
					cannotDo(_("Ticket was closed, can't add new services."));					
				} else if (data == 2) {					
					cannotDo(_("None of a service in this package is available"));					
				}		
				viewOpenTicket($('#ticket_id').val());																							
			}			
		});
	}

	//////////////////////// COMPOSITE SERVICE ///////////
	/////////////// POP UP WINDOW TO SELECT COMPOSITE SERVICE ITEMS /////////////	
	// 1. ajax get all service item of current composite service
	// 2. onSuccess, popup the window

	$(document).ready(function() {	
		$('#add_composite_service').click(function() {
			var compositeId = $('select#composite_service').val();
			// PRECHECK
			$.ajax({
				url:		"../Ticket/CheckReadyToAddCompositeServiceAjax?set_ajax_view",
				data:		"ticket_id=" + $('#ticket_id').val() +
							"&composite_service_id="	+ compositeId,
				dataType:	"json",							
				success:	function(result) {
					// ticket is closed
					if (result.status == 0) {
						cannotDo(result.body);
						return;
					}							
					
					// duplicated service
					if (result.status == 1) {
						promptConfirm('', result.body, function() {											
							addCompositeServiceAjax();
							return true;
							},'NextCancel','',_('Cancel'));
					}
					
					// empty composite service
					if (result.status == 2) {
					//no button
						generalDialog(null,null,result.body);
					}					
					
					// ready
					if (result.status == -1) {
						addCompositeServiceAjax();
					}						
				}
			});
		
			
		});
	});		
	
	/////////////// POP UP COMPOSITE SERVICE /////////////
	//
	function popUpCompositeService(compositeId) {
		
		$.ajax({
			type:		"GET",
			url:		"../CompositeService/ListItemAjax?set_ajax_view",
			data:		"composite_service_id=" + compositeId + 
						"&ticket_id=" + $('#ticket_id').val(),
			beforeSend:	function() {
				$('#add_composite_service').attr('disabled', 'disabled');
				$('div#loading').show('fast');
			},
			complete: function(){			
				$('#add_composite_service').removeAttr('disabled');
				$('div#loading').hide('fast');
			},
			success: 	function(data) {					
				$('div#add_composite_service_dialog').find('table#composite_service_item_data').remove();
				$('div#add_composite_service_dialog').find('input#composite_service_id').remove();
				$('div#add_composite_service_dialog').append(data);				
				var buttons = {};
				buttons[_('Add')] = function() {
					addCompositeServiceAjax();
					$(this).dialog('close');		
				};
				generalDialog('add_composite_service_dialog',null,null,null,{
					autoOpen: true,			
					bgiframe: true,
					resizable: true,		
					width: 700,
					height: 400,
					modal: true,
					buttons:buttons
				});
				
			}
		});
	}
	
	/////////////// ADD A COMPOSITE SERVICE /////////////
	
	
	function addCompositeServiceAjax() {						
	
/*		var queryString = "";
		var inputArray = new Array();
		$('#add_composite_service_dialog').find('input.composite_service_item_popup').each(function() {			
			if ($(this).is(":checked")) {			
				queryString += "&composite_service_item[]=" + $(this).attr('value');
				inputArray.push($(this).attr('value'));
			}
		});
		
		if (inputArray.length == 0) {
			$('div#add_composite_service_dialog').dialog('close');
			return false;
		}	
*/
		$.ajax ({
			type:	"GET",
			url: 	"../Ticket/AddCompositeServiceAjax?set_ajax_view",
			data: 	"ticket_id=" +	$('input#ticket_id').val() + 
					"&composite_service_id=" + $('select#composite_service').val(),
			beforeSend:	function() {
				$('#add_composite_service').attr('disabled', 'disabled');					
				$('div#loading').show('fast');
				$('div#add_composite_service_dialog').dialog('close');
			},
			complete: function(){	
				$('#add_composite_service').removeAttr('disabled');								
				$('div#loading').hide('fast');					
			},
			success: function(result) {								
				//$('table#ticket_item tbody').append(result);
				viewOpenTicket($('#ticket_id').val());												
			}
		});			
	}
	function updateCompositeServiceAjax(){
		var queryString = "";
		var inputArray = new Array();
		$('#update_composite_service_dialog').find('input.composite_service_item_popup').each(function() {			
			if ($(this).is(":checked")) {			
				queryString += "&composite_service_item[]=" + $(this).attr('value');
				inputArray.push($(this).attr('value'));
			}
		});
		
		if (inputArray.length == 0) {
			$('div#update_composite_service_dialog').dialog('close');
			return false;
		}	

		$.ajax ({
			type:	"GET",
			url: 	"../Ticket/UpdateCompositeServiceAjax?set_ajax_view",
			data: 	"ticket_id=" +	$('input#ticket_id').val() + 
					"&ticket_item_id=" + $('input#update_ticket_item_id').val() +
					"&composite_service_id=" + $('input#composite_service_id').val() + queryString,
			beforeSend:	function() {
				$('#update_composite_service').attr('disabled', 'disabled');					
				$('div#loading').show('fast');
				$('div#update_composite_service_dialog').dialog('close');
			},
			complete: function(){	
				$('#update_composite_service').removeAttr('disabled');								
				$('div#loading').hide('fast');					
			},
			success: function(result) {								
				//$('table#ticket_item tbody').append(result);
				viewOpenTicket($('#ticket_id').val());												
			}
		});			
	
	}
	
	function compositeServiceDetail(ticketItemId, status) {		
		$('#update_ticket_item_id').val(ticketItemId);			
		$.ajax({
			type:		"GET",
			url:		"../TicketItem/CompositeServiceDetailAjax?set_ajax_view",
			data: 		"ticket_item_id=" + ticketItemId,
			success:	function(data) {
				if (status == 'closed'){
					$('div#composite_service_detail_dialog').find('table#composite_service_item_data').remove();
					$('div#composite_service_detail_dialog').find('input#composite_service_id').remove();
					$('div#composite_service_detail_dialog').append(data);	
					var buttons = {};					
					buttons[_('Close')] = function() {
							$(this).dialog('close');		
						};
					generalDialog('composite_service_detail_dialog',null,null,null,{
							autoOpen: true,			
							bgiframe: true,
							resizable: true,
							modal: true,
							width: 700,
							height: 400,
							buttons: buttons
						});				
					
				} else {
					$('div#update_composite_service_dialog').find('table#composite_service_item_data').remove();
					$('div#update_composite_service_dialog').find('input#composite_service_id').remove();
					$('div#update_composite_service_dialog').append(data);
					var buttons = {};
					buttons[_('Close')] = function() {
						$(this).dialog('close');		
					};
					buttons[_('Save')] = function() {
						updateCompositeServiceAjax();						
						$(this).dialog('close');		
					};					
					generalDialog('update_composite_service_dialog',null,null,null,{
							autoOpen: true,			
							bgiframe: true,
							resizable: true,
							modal: true,	
							width: 700,
							height: 400,
							buttons: buttons
						});	
				}
			}			
		});
	}		

	
	/////////////// POP UP PARACLINIC ASSIGNMENT /////////////	
	// 1. ajax get all test item of current test
	// 2. onSuccess, popup the window
	$(document).ready(function() {	
		$('#addParaClinic').click(function() {			
			var enumParaClinic = $('select#paraClinicService').val();
			// PRECHECK
			$.ajax({
				url:		"../Ticket/RenderParaclinicAssignmentAjax?set_ajax_view",
				data:		"ticket_id=" + $('#ticket_id').val()
							+ "&enumParaClinic=" + enumParaClinic,
				dataType:	"json",							
				success:	function(data) {
					if (data.error.code ==  'OK') {
						$('#paraClinicAssignment').html(data.result);						
					} else {
						displayError(data.error.mess);				
					}											
				}
			});
		
			
		});
	});		
	
	/////////////// POP UP TEST SERVICE /////////////
	//
	function popUpTest(testId) {
		
		$.ajax({
			type:		"GET",
			url:		"../Test/ListItemAjax?set_ajax_view",
			data:		"test_id=" + testId,
			beforeSend:	function() {
				$('#add_test').attr('disabled', 'disabled');
				$('div#loading').show('fast');
			},
			complete: function(){			
				$('#add_test').removeAttr('disabled');
				$('div#loading').hide('fast');
			},
			success: 	function(data) {					
				$('div#add_test_dialog').find('table#test_item_data').remove();
				$('div#add_test_dialog').find('input#test_id').remove();
				$('div#add_test_dialog').append(data);
				var buttons = {};
				buttons[_('Add test')] = function() {
					addTestAjax();
					$(this).dialog('close');		
				};
				generalDialog('add_test_dialog',null,null,null,{
					autoOpen: true,			
					bgiframe: true,
					resizable: true,		
					width: 700,
					height: 400,
					modal: true,
					buttons:buttons
				});
				
			}
		});
	}
	
	/////////////// ADD A TEST SERVICE /////////////
	// ajax add an test item
	$(document).ready(function() {		
		$('#add_test_popup').click(function() {							
			addTestAjax();
		});
	});
	
	function addTestAjax() {
		var queryString = "";
		var inputArray = new Array;
		$('input.test_item_popup').each(function() {			
			if ($(this).is(":checked")) {			
				queryString += "&test_item[]=" + $(this).attr('value');
				inputArray.push($(this).attr('value'));
			}
		});
		
		if (inputArray.length == 0) {
			$('div#add_test_dialog').dialog('close');			
			return false;
		}	
		
		$.ajax ({
			type:	"GET",
			url: 	"../Ticket/AddTestAjax?set_ajax_view",
			data: 	"ticket_id=" +	$('input#ticket_id').val() + 
					"&test_id=" + $('input#test_id').val() + queryString,
			beforeSend:	function() {
				$('#add_test').attr('disabled', 'disabled');					
				$('div#loading').show('fast');				
				$('div#add_test_dialog').dialog('close');
			},
			complete: function(){	
				$('#add_test').removeAttr('disabled');								
				$('div#loading').hide('fast');					
			},
			success: function(result) {				
				//$('table#ticket_item tbody').append(result);
				viewOpenTicket($('#ticket_id').val());												
			}
		});			
	}
	
		
	/////////////// POP UP LAB ASSIGNMENT /////////////	
	// ajax show test details
	function labAssignmentDetail(ticketId, labAssignmentTicketId) {	
		var idOfActionAfterUpdating = 'refreshParaClinic';
		$.ajax({
			type:		"GET",
			url:		"../Ticket/BuildLabAssignment4VEditAjax?set_ajax_view",
			data:		"ticketId=" + ticketId 
			+ "&idOfActionAfterUpdating=" + idOfActionAfterUpdating
			+ "&labAssignmentTicketId=" + labAssignmentTicketId,		
			dataType:   "json",
			success: 	function(data) {

			if (data.error.code ==  'OK') {
				$("div#paraClinicAssignment").html(data.result);			

			} else {
				displayError(data.error.mess);				
			}

		}
		});	
	}
	// delete a ticket item
	function deleteLabTicketItem(ticketItemId, labAssignmentTicketId) {	
		var serviceName = $('tr#' + ticketItemId).children('td:nth-child(3)').text();
		promptConfirm(_('Delete'), _('Are you sure to delete <span class="impression">{0}</span> service?',serviceName), function() {											
			deleteLabTicketItemSubmit(ticketItemId, labAssignmentTicketId);
			return true;
			},'YesNo','warn',_('No'));	
		
	}
	
	
	function deleteLabTicketItemSubmit(ticketItemId, labAssignmentTicketId) {
		$.ajax({
			type:		"GET",
			url:		"../Ticket/DeleteLabAssignmentTicketAjax?set_ajax_view",
			data:		"labAssignmentTicketId=" + labAssignmentTicketId,		
			dataType:   "json",
			success: 	function(data) {

			if (data.error.code ==  'OK') {
				deleteTicketItemSubmit(ticketItemId);

			} else {
				displayError(data.error.mess);				
			}

		}
		});
	}
	
	// Delete a ticket item of radiology type
	function deleteRadTicketItem(ticketItemId, radTicketId) {
	   var serviceName = $('tr#' + ticketItemId).children('td:nth-child(3)').text();
        promptConfirm(_('Delete'), _('Are you sure to delete <span class="impression">{0}</span> service?',serviceName), function() {                                           
            deleteRadTicketItemSubmit(ticketItemId, radTicketId);
            return true;
            },'YesNo','warn',_('No'));  
	}
	
	function deleteRadTicketItemSubmit(ticketItemId, radTicketId) {
	   $.ajax({
            type:       "GET",
            url:        "../Ticket/DeleteRadAssignmentTicketAjax?set_ajax_view",
            data:       "radTicketId=" + radTicketId,       
            dataType:   "json",
            success:    function(data) {
	            if (data.error.code ==  'OK') {
	                deleteTicketItemSubmit(ticketItemId);
	            } else {
	                displayError(data.error.mess);              
	            }
            }
        });
	}
	
	function radAssignmentDetail(radTicketId, enumRadType) {
	   var idOfActionAfterUpdating = 'refreshParaClinic';
	   $.ajax({
            type:       "GET",
            url:        "../Ticket/LoadRadAssignmentEditAjax?set_ajax_view",
            data:       "radTicketId=" + radTicketId + "&radType=" + 
                        enumRadType + "&triggeredElement=" + idOfActionAfterUpdating,  
            dataType:   "json",
            success:    function(data) {
                if (data.error.code ==  'OK') {
                    $("div#paraClinicAssignment").html(data.result);
                } else {
                    displayError(data.error.mess);              
                }
            }
        });
	}
//////////////////////// VIEW OPEN TICKET ///////////////

function viewOpenTicket(ticketId) {
	$('div#intro_sentence').hide();		
	$('input#ticket_id').attr('value', ticketId);
	
	$.ajax({
		type:		"GET",
		url:		"../Ticket/ViewOpenTicketAjax?set_ajax_view",
		data:		"ticket_id=" + ticketId,
		dataType:	"json",
		beforeSend:	function() {						
			$('div#loading').show();			
		},
		complete: 	function() {
			$('div#loading').hide();			
		},
		success:	function(data) {													
			$('span#open_ticket_name').text(data.ticket_name);
			
			$('div#add_ticket').show('slow');	
			$('div#view_closed_ticket').hide();						
			if (data.ticket_body == "") {
				$('table#ticket_item').hide();
				return true;
			} else {
				$('table#ticket_item tbody').html(data.ticket_body);				
				styleTicketItemTable($('table#ticket_item'));
				styleCancelTicketButton();									
				$('table#ticket_item').show();
				
				$('#ticket_item tr.contextMenu').contextMenu('ticketItemMenu', {
					bindings: {
	        			'open': changeTicketItemFee
	      			}
    			});
			}				
		}		
	});
	
}


function changeTicketItemFee(t) {
	var message = _("<span>Adjustment of service fee </span><span style='color: red'>{0}</span>", $('tr#' + t.id + ' td:eq(2)').text())
		+ "<br/>" 
		+ "<table class='dialogTable'>"
		+ "<tr><td colspan='2'><span id='changeFeeMessage' style='color: red;'></span><td></tr>"
		+ "<tr>"
		+ "<td style='width: 100px'>"
		+ _("Real fee")
		+ "</td>"
		+ "<td>"		 
		+ "<input type='text' name='newFee' id='newFee' value='' style='width: 200px'/>"
		+ "</td>"
		+ "<tr>"
		+ "<td>"
		+ _("Reason")
		+ "</td>"
		+ "<td>"
		+ "<input type='text' name='newFee' id='reason' value='' style='width: 200px'/>"
		+ "</td>"
		+ "<tr>"
		+ "</table>";
		
			
	var buttons = {};
	buttons[_('Cancel')] = function() {
		$(this).dialog('close');
	};
	buttons[_('Update')] = function() {		
			var newFee = $.trim($('#newFee').val());									
			if (newFee == '' || isNaN(newFee) || newFee < 0) {
				$('#newFee').css('border-color', 'red');
				$('span#changeFeeMessage').html(_('Invalid Fee'));
			} else {										
				changeFee(t.id, newFee);
				$(this).dialog('close');
			} 																									
		};
	
	generalDialog(null,null,message,null,{
		autoOpen: true,			
		bgiframe: true,
		resizable: false,		
		modal: true,
		width: 380,
		title: _('Change Fee'),							
		buttons: buttons
	},_('Cancel'));
}


	///////////////////// STYLE ticket_item TABLE AFTER EACH CHANGES /////////
	//
	function styleTicketItemTable(table) {		
		var downItems = table.find('a.down_item').length;
		var upItems = table.find('a.up_item').length;
		if ((downItems == 1 && upItems == 0) ||
			(downItems == 0 && upItems == 1)) {
			table.find('a.down_item').parent().html('&nbsp;');
			table.find('a.down_item').remove();
			table.find('a.up_item').parent().html('&nbsp;');
			table.find('a.up_item').remove();
		}
		table.find('tr:last-child').addClass('last');			
				
		table.find('a.elementDisabled').parent().text(' ');
		table.find('a.elementDisabled').remove();					
	}

	function styleCancelTicketButton() {
		if ($('table#ticket_item').find('.elementDisabled').length > 0) {			
			$('#cancel').hide();
		} else {
			$('#cancel').show();			
		}	
	}
	
	function appendMoney(payment) {
		$('#total_amount').text(payment.total_price);
		$('#patient_amount').text(payment.patient_price);		
		$('#real_amount').text(payment.real_price);
		
		$('#prescription_amount').text(payment.prescription_price);	
		$('#discount_amount').text(payment.discount_price);																	
	}

	
	//////////////////////// DELETE TICKET ITEM  ///////////////
	// delete a ticket item
	function deleteTicketItem(ticketItemId) {	
		var serviceName = $('tr#' + ticketItemId).children('td:nth-child(3)').text();
		promptConfirm(_('Delete'), _('Are you sure to delete <span class="impression">{0}</span> service?',serviceName), function() {											
			deleteTicketItemSubmit(ticketItemId);
			return true;
			},'YesNo','warn',_('No'));	
		
	}
	
	function deleteTicketItemSubmit(ticketItemId) {	
		$.ajax ({
			type:		"GET",
			url:		"../TicketItem/DeleteAjax?set_ajax_view",
			data:		"ticket_item_id=" + ticketItemId,
			beforeSend:	function() {				
				$('div#loading').show('fast');				
			},
			success:	function(result) {
				// cannot delete ticket item
				if (result == false) {
					cannotDo(_('Can not delete this service'));
					return;
				}		
				$('tr#' + ticketItemId).fadeOut('slow').remove();																	
				viewOpenTicket($('#ticket_id').val());										
			}
		});	
	}
	
	///////////////////// SET A TICKET ITEM TO STATUS IN_WAITING /////////
	//
	//
	function waitForParaClinicService(ticketItemId) {
		var serviceName = $('tr#' + ticketItemId).children('td:nth-child(3)').text();
			
		promptConfirm(_('Confirm'), _("Are you sure to wait for the result of service <span class=\"impression\">{0} </span>?", serviceName), function() {											
			submitWaitForParaClinicService(ticketItemId);
			return true;
			},'YesNo','',_("No"));
	}
	
	function submitWaitForParaClinicService(ticketItemId) {
		$.ajax ({
			type:		"GET",
			url:		"../TicketItem/WaitForParaClinicServiceAjax?set_ajax_view",
			data:		"ticket_item_id=" + ticketItemId,
			dataType:	"json",
			beforeSend:	function() {				
				$('div#loading').show('fast');
			},
			complete:	function() {				
				$('div#loading').hide('fast')
			},
			success:	function(data) {
				$('#ticket_item tbody tr#' + ticketItemId).remove('a.up_item');
				$('#ticket_item tbody tr#' + ticketItemId).remove('a.down_item');				
				var message = _('Next location: <span class="bigImpression">{0}</span>',data.roomName) ;
				//no button
				generalDialog(null,null,message);	
				window.location=data.redirectLink;														
			}
		});	
	}
	
	///////////////////// COMPLETE A TICKET_ITEM /////////
	//
	//
	function completeTicketItem(ticketItemId) {
		var message = '';
		var lastService = false;
		if ($('tr#' + ticketItemId).next().length == 0) {
			message = '<p>'
				+ _("<span class='impression'>Notice:</span> This is the last service, it's unable to add new service after closing it.")
				+ '</p>';
			lastService = true;	
		}
		var serviceName = $('tr#' + ticketItemId).children('td:nth-child(3)').text();
		
		if (lastService) {
			//focus 0
			promptConfirm(_('Confirm'), _('Are you sure to finish <span class="impression">{0} </span>service?',serviceName ) + message, function() {											
				submitCompleteTicketItem(ticketItemId);
				return true;
				},'YesNo','',_('Yes'));
		} else {
			submitCompleteTicketItem(ticketItemId);
		}
			
	}
	
	function submitCompleteTicketItem(ticketItemId) {				
		$.ajax ({
			type:		"GET",
			url:		"../TicketItem/CompleteAjax?set_ajax_view",
			data:		"ticket_item_id=" + ticketItemId,
			dataType:	"json",
			beforeSend:	function() {				
				$('div#loading').show('fast');
			},
			complete:	function() {				
				$('div#loading').hide('fast')
			},
			success:	function(data) {
				$('#ticket_item tbody tr#' + ticketItemId).remove('a.up_item');
				$('#ticket_item tbody tr#' + ticketItemId).remove('a.down_item');
				$('#ticket_item tbody tr#' + ticketItemId).find('.elementEnable').remove();								
				
				if (data.roomName == "closed") {
					var message = '<span class="bigImpression">' + _("Collected") + '</span>';					
				} else {
					var message = _('Next location: <span class="bigImpression">{0}</span>',data.roomName) ;				
				}
				//no button
				generalDialog(null,null,message);		
				window.location=data.redirectLink;							
			}
		});
	}
	
	
	///////////////////// CONTINUE A TICKET_ITEM /////////
	//
	//
	function continueEncounter(ticketItemId) {
		var serviceName = $('tr#' + ticketItemId).children('td:nth-child(3)').text();
		//focus 1
		promptConfirm(_('Confirm'), _('Are you sure to continue examination <span class="impression">{0} </span>?',serviceName), function() {											
			submitContinueEncounter(ticketItemId);
			return true;
			},'YesNo','',_('No'));
	}
	
	function submitContinueEncounter(ticketItemId) {
		$.ajax ({
			type:		"GET",
			url:		"../TicketItem/ContinueEncouterAjax?set_ajax_view",
			data:		"ticket_item_id=" + ticketItemId,
			beforeSend:	function() {				
				$('div#loading').show('fast');
			},
			complete:	function() {				
				$('div#loading').hide('fast')
			},
			success:	function(data) {											
				$('#ticket_item tbody tr#' + ticketItemId).find('td:nth-child(9)').text(_('Examining'));
				var cont = '<a class="elementEnable" href="javascript:waitForParaClinicService(' + ticketItemId + ');">' + _("Test") + '</a>';
				$('#ticket_item tbody tr#' + ticketItemId).find('td:nth-child(11)').html(cont);	
			}
		});	
	}
	
	//////////////////// TURN UP/DOWN A TICKET ITEM ////////////
	//
	//
	function turnDown(ticketItemId) {
		var serviceName = $('tr#' + ticketItemId).next().children('td:nth-child(3)').text();
		
		$.ajax ({
			type:		"GET",
			url:		"../Ticket/TurnDownAjax?set_ajax_view",
			data:		"ticket_item_id=" + ticketItemId,
			beforeSend:	function() {				
				$('div#loading').show('fast');
			},
			complete:	function() {				
				$('div#loading').hide('fast')
			},
			success:	function(data) {
				if (data == 1) {
					// change order of IN-PROGRESS item
					popUpDoctorList(ticketItemId, serviceName, 'down');
				} else {					
					viewOpenTicket($('#ticket_id').val());
				}														
			}
		});	
	}
	
	function turnUp(ticketItemId) {
		var serviceName = $('tr#' + ticketItemId).children('td:nth-child(3)').text();
		$.ajax ({
			type:		"GET",
			url:		"../Ticket/TurnUpAjax?set_ajax_view",
			data:		"ticket_item_id=" + ticketItemId,
			beforeSend:	function() {				
				$('div#loading').show('fast');
			},	
			complete:	function() {				
				$('div#loading').hide('fast')
			},		
			success:	function(data) {											
				if (data == 1) {
					// change order of IN-PROGRESS item
					popUpDoctorList(ticketItemId, serviceName, 'up');
				} else {					
					viewOpenTicket($('#ticket_id').val());
				}
			}
		});	
	}
	
	function popUpDoctorList(ticketItemId, serviceName, direction) {
		$.ajax({
			type:	"GET",
			url:	"../Ticket/GetDoctorList?set_ajax_view",						
			success: function(data) {
				var message = '<p>'
					+ _('Select Dr/Technician <span class="impression">{0}</span>',serviceName)
					+ '</p>' + data;
				promptConfirm('', message, function() {											
					submitTurning(ticketItemId, $('#doctorList').val(), direction);
					return true;
					},'SelectCancel');
			}
		});
	}
	
	function submitTurning(ticketItemId, doctorId, direction) {
		$.ajax({
			type:	"GET",
			url:	"../Ticket/SubmitTurning?set_ajax_view",
			data: 	'ticket_item_id=' + ticketItemId +
					'&doctor_id=' + doctorId +
					'&direction=' + direction,						
			success: function(data) {
				viewOpenTicket($('#ticket_id').val());		
			}
		});
	}
	
	function changeFee(ticketItemId, newFee) {
		var reason = $("input#reason").val();		
		$.ajax ({
			type:		"POST",
			url:		"../Ticket/UpdateNewFeeAjax?set_ajax_view",
			data:		"itemId=" + ticketItemId + "&newFee=" + newFee + "&reason=" + reason,		
			success:	function(data) {
				viewOpenTicket($('#ticket_id').val());															
			}
		});	
	}
			